package com.habdqn.studentmanager.converter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

public class DateConverter implements Converter<String, Date> {
	
	private static Logger logger = LoggerFactory.getLogger(DateConverter.class);
	
	private static final String DATEFORMAT = "yyyy-MM-dd";
	
	private static final String TIMEFORMAT = "yyyy-MM-dd HH:mm:ss";

	@Override
	public Date convert(String source) {

		if (StringUtils.isEmpty(source)) {
			return null;
		}
		
		try {
			SimpleDateFormat sdf = getDateFormat(source);
			
			if (null == sdf) {
				return null;
			}
			
			sdf.setLenient(false);
			return sdf.parse(source);
		}
		catch (Exception e) {
			logger.error("cannot parse value[{}] to date", source, e);
		}

		return null;
	}

	/**
	 * 根据日期格式实例化相应的DateFormat对象
	 */
	private SimpleDateFormat getDateFormat(String value) {
		
		Pattern pattern = null;
		Matcher matcher = null;

		try {
			// yyyy-MM-dd
			pattern = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}$");
			matcher = pattern.matcher(value);
			if (matcher.matches()) {
				return new SimpleDateFormat(DATEFORMAT);
			}

			// yyyy-MM-dd HH:mm:ss
			pattern = Pattern.compile("^\\d{4}\\-\\d{1,2}\\-\\d{1,2}\\s{1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");
			matcher = pattern.matcher(value);
			if (matcher.matches()) {
				return new SimpleDateFormat(TIMEFORMAT);
			}
			
		}
		catch (PatternSyntaxException e) {
			logger.debug("cannot parse value[{}] to date", value, e);
		}
		
		return null;
	}

}
